package cn.weixin.song.controller.api.handle;

import java.util.Date;
import java.util.List;

import cn.weixin.song.contant.R.ModelType;
import cn.weixin.song.model.Music;
import cn.weixin.song.model.MusicActivity;
import cn.weixin.song.model.MusicActivityPlayRecord;
import cn.weixin.song.model.MusicActivityQuestion;
import cn.weixin.song.model.User;
import cn.weixin.song.model.UserModelPlay;

import com.github.sd4324530.fastweixin.handle.MessageHandle;
import com.github.sd4324530.fastweixin.message.Article;
import com.github.sd4324530.fastweixin.message.BaseMsg;
import com.github.sd4324530.fastweixin.message.NewsMsg;
import com.github.sd4324530.fastweixin.message.RespType;
import com.github.sd4324530.fastweixin.message.TextMsg;
import com.github.sd4324530.fastweixin.message.req.TextReqMsg;
import com.google.common.collect.Lists;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.DateUtils;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;

public class MusicGameMsgHandle implements MessageHandle<TextReqMsg>{

	private String wid;
	
	private User user;
	
	public MusicGameMsgHandle(String wid){
		this.wid=wid;
	}
	@Override
	public BaseMsg handle(TextReqMsg msg) {
		String content=msg.getContent().toUpperCase();
		MusicActivity musicActivity=MusicActivity.dao.getLastMusicActivity(wid);
		MusicActivityPlayRecord musicActivityPlayRecord=MusicActivityPlayRecord.dao.getMusicActivityPlayRecord(user.getInt("id"),musicActivity.getInt("id"));
		if(musicActivityPlayRecord==null){ 
			musicActivityPlayRecord=MusicActivityPlayRecord.dao.initMusicActivityPlayRecord(user.getInt("id"),musicActivity.getInt("id"));
		}
		if(DateUtils.dateIsExpire(musicActivity.getDate("end_time"), 0)){
			return  new TextMsg("本期活动已结束,回复L可查看最新排名");
		}
		if(content.equals("G")){//开始闯关或继续闯关
			if(musicActivityPlayRecord.getInt("last_status").equals(1)&&musicActivityPlayRecord.getInt("current_level").equals(musicActivity.getInt("level_count"))){
				return  new TextMsg("你已完成闯关，你本期活动最高的分数是:"+musicActivityPlayRecord.getInt("high_score")+"分,最后闯关获得的分数是:"+musicActivityPlayRecord.getInt("score")+"分\r\n发送\"L\"可查看最新排行榜\r\n发送\"R\"再玩一次");
			}
			if(musicActivityPlayRecord.getInt("last_status").equals(1)){
				new TextMsg("已完成每"+musicActivityPlayRecord.getInt("current_level")+"关卡,回复\"N\"继续下一关");
			}
			return getMusicMsg(msg, musicActivity, musicActivityPlayRecord);
		}else if(content.equals("N")){//下一关卡
			if(DateUtils.dateIsExpire(musicActivity.getDate("end_time"), 0)){
				return  new TextMsg("本期活动已结束,回复L可查看最新排名");
			}
			if(musicActivityPlayRecord.getInt("last_status").equals(1)&&musicActivityPlayRecord.getInt("current_level").equals(musicActivity.getInt("level_count"))){
				return  new TextMsg("你已完成闯关，你本期活动最高的分数是:"+musicActivityPlayRecord.getInt("high_score")+"分,最后闯关获得的分数是:"+musicActivityPlayRecord.getInt("score")+"分\r\n发送\"L\"可查看最新排行榜\r\n发送\"R\"再玩一次");
			}
			//如果上一关卡已完成则设置跳到下一关卡
			if(musicActivityPlayRecord.getInt("last_status").equals(1)){
				nextLevel(musicActivity, musicActivityPlayRecord);
			}
			return getMusicMsg(msg, musicActivity, musicActivityPlayRecord);
		}else if(content.equals("R")){//重置游戏
			if(musicActivityPlayRecord!=null){
				if(user.getInt("gold_coin")<5){
					return  new TextMsg("剩余金币不足5个，无法重置游戏，发送\"Y\"赚金币");
				}
				user.set("gold_coin", user.getInt("gold_coin")-5).update();
				musicActivityPlayRecord.set("last_status", 0).set("current_level", 0).set("score", 0)
				.set("last_music_id", null)
				.set("spend_time", 0l).update();
				return  new TextMsg("重置游戏成功，发送\"G\"继续游戏");
			}
			return  new TextMsg("还没参与活动，发送\"G\"开始游戏");
		}else if(content.equals("L")){//查看最新排名
			String str=MusicActivityPlayRecord.dao.getMusicActivityPlayRecordRanks(musicActivity.getInt("id"));
			if(musicActivityPlayRecord!=null){
				str+="\r\n"+MusicActivityPlayRecord.dao.getMyRank(musicActivity.getInt("id"), musicActivityPlayRecord.getInt("high_score"), musicActivityPlayRecord.getLong("high_spend_time"));
			}
			long userCount=MusicActivityPlayRecord.dao.getCount(CommonUtils.getConditions(new Condition("music_activity_id",Operators.EQ,musicActivity.getInt("id"))));
			str+="\r\n目前参与人数:"+userCount+"人\r\n";
			return  new TextMsg(str);
		}else if(content.equals("Y")){//邀请赚金币
			String inviteCode=User.dao.getMyInviteCode(user.getInt("id"));
			List<Article> articles=Lists.newArrayList();
			Article article=new Article();
			article.setTitle("欢乐猜歌闯关赢话费");
			article.setPicUrl("https://mmbiz.qlogo.cn/mmbiz/hs0gCiba6kHcATicMfNVwPUCnfMVdvMC4jcx8YBSMDQHfTIbicvTmcHWtsXwUM2BwBb5umT38HksADnOpJvYPibmHg/0?wx_fmt=png");
			article.setUrl("http://mp.weixin.qq.com/s?__biz=MjM5OTA2OTkyOA==&mid=400802810&idx=1&sn=98f9fd211d6e7721d3d30577d34913a6&scene=0&previewkey=bMnWTvevfpyoXXPwQ0izTMwqSljwj2bfCUaCyDofEow%3D#wechat_redirect");
			article.setDescription("你的邀请码是："+inviteCode+"，邀请1人各奖励10金币。分享文字示例：发送s@"+inviteCode+"可获得奖励并参与猜歌游戏");
			articles.add(article);
			return new NewsMsg(articles);
		}
		if(musicActivityPlayRecord.getInt("last_status").equals(1)&&musicActivityPlayRecord.getInt("current_level").equals(musicActivity.getInt("level_count"))){
			return  new TextMsg("你已完成闯关，你本期活动最高的分数是:"+musicActivityPlayRecord.getInt("high_score")+"分,最后闯关获得的分数是:"+musicActivityPlayRecord.getInt("score")+"分\r\n发送\"L\"可查看最新排行榜\n发送\"R\"再玩一次");
		}
		if(musicActivityPlayRecord.getInt("last_status").equals(1)){
			return new TextMsg("已完成每"+musicActivityPlayRecord.getInt("current_level")+"关卡,回复\"N\"继续下一关");
		}
		//判断回答是否超时
		if(DateUtils.dateIsExpire(musicActivityPlayRecord.getDate("last_play_date"), musicActivity.getInt("level_think_minute"))){
			    //更新回答状态 1-已完成回答
				musicActivityPlayRecord.set("last_status", 1);
				long m_spend_time=new Date().getTime()-musicActivityPlayRecord.getDate("last_play_date").getTime();
				//更新思考总时间
				musicActivityPlayRecord.set("spend_time", musicActivityPlayRecord.getLong("spend_time")+m_spend_time);
				//判断是否是最后一关卡
				if(musicActivityPlayRecord.getInt("current_level").intValue()==musicActivity.getInt("level_count").intValue()){
					updateHighScore(musicActivityPlayRecord);
					return  new TextMsg("当前关卡回答超时。已完成所有关卡,总分:"+musicActivityPlayRecord.getInt("score")+"\r\n总耗时："+musicActivityPlayRecord.getLong("spend_time")+"\r\n发送\"L\"可查看最新排行榜\r\n发送\"R\"再玩一次");
				}else{
					musicActivityPlayRecord.update();
					return  new TextMsg("当前关卡回答超时。回复\"N\"进入下一关卡");
				}
		}
		Music music=Music.dao.findById(musicActivityPlayRecord.getInt("last_music_id"));
		if(music.getStr("name").equals(content)){//回答正确
			musicActivityPlayRecord.set("last_status", 1).set("score", musicActivityPlayRecord.getInt("score")+music.getScore());
			long m_spend_time=new Date().getTime()-musicActivityPlayRecord.getDate("last_play_date").getTime();
			musicActivityPlayRecord.set("spend_time", musicActivityPlayRecord.getLong("spend_time")+m_spend_time);
			if(musicActivityPlayRecord.getInt("current_level").intValue()==musicActivity.getInt("level_count").intValue()){
				updateHighScore(musicActivityPlayRecord);
				StringBuffer sb=new StringBuffer("恭喜你已完成所有关卡\r\n总分："+musicActivityPlayRecord.getInt("score")+"\r\n总耗时："+musicActivityPlayRecord.getLong("spend_time")+"\r\n发送\"L\"可查看最新排行榜\r\n发送\"R\"再玩一次");
				return  new TextMsg(sb.toString());
			}else{
				musicActivityPlayRecord.update();
				nextLevel(musicActivity, musicActivityPlayRecord);
				return this.getMusicMsg(msg, musicActivity, musicActivityPlayRecord);
				//return  new TextMsg("回答正确，当前分数："+musicActivityPlayRecord.getInt("score")+"分,回复\"N\"进入下一关卡");
			}
		}else{
			musicActivityPlayRecord.set("last_status", 1);
			long m_spend_time=new Date().getTime()-musicActivityPlayRecord.getDate("last_play_date").getTime();
			musicActivityPlayRecord.set("spend_time", musicActivityPlayRecord.getLong("spend_time")+m_spend_time);
			if(musicActivityPlayRecord.getInt("current_level").intValue()==musicActivity.getInt("level_count").intValue()){
				updateHighScore(musicActivityPlayRecord);
				StringBuffer sb=new StringBuffer("回答不正确,正确答案是:《"+music.getName()+"》,已完成所有关卡,总分:"+musicActivityPlayRecord.getInt("score")+"\r\n总耗时："+musicActivityPlayRecord.getLong("spend_time")+"\r\n发送\"L\"可查看最新排行榜\r\n发送\"R\"再玩一次");
				return  new TextMsg(sb.toString());
			}else{
				musicActivityPlayRecord.update();
				return  new TextMsg("回答不正确,正确答案是:《"+music.getName()+"》,回复\"N\"进入下一关卡");
			}
		}
	}
	private void nextLevel(MusicActivity musicActivity,
			MusicActivityPlayRecord musicActivityPlayRecord) {
		int musicId=MusicActivityQuestion.dao.selectMusicId(musicActivity.getInt("id"),musicActivityPlayRecord.getInt("current_level")+1);
		musicActivityPlayRecord.set("current_level", musicActivityPlayRecord.getInt("current_level")+1)
		.set("last_play_date", new Date()).set("last_music_id", musicId).set("last_status", 0).update();
	}
	private void updateHighScore(MusicActivityPlayRecord musicActivityPlayRecord) {
		if(musicActivityPlayRecord.getInt("high_score")<musicActivityPlayRecord.getInt("score")){
			musicActivityPlayRecord.set("high_score", musicActivityPlayRecord.getInt("score"));
			musicActivityPlayRecord.set("high_spend_time", musicActivityPlayRecord.getLong("spend_time"));
		}
		if(musicActivityPlayRecord.getInt("high_score").equals(musicActivityPlayRecord.getInt("score"))&&
				musicActivityPlayRecord.getLong("spend_time")<musicActivityPlayRecord.getLong("high_spend_time")){
			musicActivityPlayRecord.set("high_spend_time", musicActivityPlayRecord.getLong("spend_time"));
		}
		musicActivityPlayRecord.update();
	}
	
	private BaseMsg getMusicMsg(TextReqMsg msg, MusicActivity musicActivity,
			MusicActivityPlayRecord musicActivityPlayRecord) {
		if(musicActivityPlayRecord.getInt("last_music_id")==null){//第一关
			int musicId=MusicActivityQuestion.dao.selectMusicId(musicActivity.getInt("id"),1);
			musicActivityPlayRecord.set("last_music_id", musicId).set("last_play_date", new Date()).set("current_level", 1).update();
		}
		Music music=Music.dao.findById(musicActivityPlayRecord.getInt("last_music_id"));
		MyMusicMsg musicMsg=new MyMusicMsg();
		musicMsg.setFromUserName(msg.getToUserName());
		musicMsg.setToUserName(msg.getFromUserName());
		musicMsg.setTitle("第"+musicActivityPlayRecord.getInt("current_level")+"关");
		musicMsg.setMusicUrl(PropKit.get("img_url")+music.getStr("music_url"));
		musicMsg.setHqMusicUrl(PropKit.get("img_url")+music.getStr("music_url"));
		musicMsg.setMsgType(RespType.MUSIC);
		String language="";
		if(StrKit.notBlank(music.getStr("language"))){
			language="-"+music.getStr("language");
		}
		if(music.getInt("hard_level")==1){
			musicMsg.setDescription("简单("+music.getScore()+"分)"+language);
		}else if(music.getInt("hard_level")==2){
			musicMsg.setDescription("一般("+music.getScore()+"分)"+language);
		}else if(music.getInt("hard_level")==3){
			musicMsg.setDescription("困难("+music.getScore()+"分)"+language);
		}
		return  musicMsg;
	}
	@Override
	public boolean beforeHandle(TextReqMsg msg) {
		user=User.dao.initUser(wid,msg.getFromUserName());
		int modelType=UserModelPlay.dao.getCurrentModelType(user.getId());
		return modelType==ModelType.MUSIC?true:false;
	}
}
